﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using WpfSnqkGasAnalysis.Common;
using WpfSnqkGasAnalysis.IData;
using System.IO;
using System.Text.RegularExpressions;
using WpfSnqkGasAnalysis.Model;
using WpfSnqkGasAnalysis.IBusiness_impl;

namespace WpfSnqkGasAnalysis
{
    /// <summary>
    /// 气分析，录入
    /// </summary>
    public partial class WindowAdd_Gasanalysis : Window
    {
        public WindowAdd_Gasanalysis()
        {
            InitializeComponent();
        }
        UserBusiness userBusiness = new UserBusiness();

        //下拉框数据初始化。创建时间：2022-12-6 14:23:37。作者：王浩力
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            ISource_dictDAL source_DictDAL = ServicesHelpter.GetService<ISource_dictDAL>();
            var all = source_DictDAL.GetAll();
            all = all.Where(g => g.D_stat == 1).ToList();

            //类别下拉框
            cmb_cate.ItemsSource = all.Where(g => g.Group_id.Equals("cate")).ToList();
            cmb_cate.DisplayMemberPath = "Item_name";
            cmb_cate.SelectedValuePath = "Id";

            //构造名称
            cmb_gouzao.ItemsSource = all.Where(g => g.Group_id.Equals("structure")).ToList();
            cmb_gouzao.DisplayMemberPath = "Item_name";
            cmb_gouzao.SelectedValuePath = "Id";

            //顶界层位
            cmb_topCeng.ItemsSource = all.Where(g => g.Group_id.Equals("cengwei")).ToList();

            //底界层位
            cmb_bottomCeng.ItemsSource = all.Where(g => g.Group_id.Equals("cengwei")).ToList();

            //取样位置
            var qylist = all.Where(g => g.Group_id.Equals("quyangLocation")).ToList();
            qylist.Insert(0, new Source_dict() { Id = 0, Item_name = "请选择" });
            cmb_quyang.ItemsSource = qylist;
            cmb_quyang.DisplayMemberPath = "Item_name";
            cmb_quyang.SelectedValuePath = "Id";

            //取样单位
            cmb_samping_company_name.ItemsSource = all.Where(g => g.Group_id.Equals("quyang")).ToList();
            cmb_samping_company_name.DisplayMemberPath = "Item_name";
            cmb_samping_company_name.SelectedValuePath = "Id";

            //分析单位
            cmb_analysis_company_name.ItemsSource = all.Where(g => g.Group_id.Equals("quyang")).ToList();
            cmb_analysis_company_name.DisplayMemberPath = "Item_name";
            cmb_analysis_company_name.SelectedValuePath = "Id";

            //取样条件
            cmb_samping_condition.ItemsSource = all.Where(g => g.Group_id.Equals("quyangCondition")).ToList();
            cmb_samping_condition.DisplayMemberPath = "Item_name";
            cmb_samping_condition.SelectedValuePath = "Id";

            //委托单位
            cmb_client.ItemsSource = all.Where(g => g.Group_id.Equals("quyang")).ToList();
            cmb_client.DisplayMemberPath = "Item_name";
            cmb_client.SelectedValuePath = "Id";

            //取样人          
            var userList = userBusiness.GetAllUser();
            userList = userList.FindAll(g => g.U_stat == 1);
            samping_user.ItemsSource = userList;
            samping_user.DisplayMemberPath = "User_real_name";
            samping_user.SelectedValuePath = "Id";

            //分析人
            analysis_user.ItemsSource = userList;
            analysis_user.DisplayMemberPath = "User_real_name";
            analysis_user.SelectedValuePath = "Id";

            //所有输入框，增加数字验证//2022-12-7 14:50:46
            //var gg = this.LogicalChildren;
            //var childs = this.GetTemplateChild("TextBox");

        }

        //导入，右侧指标数据
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            GasCommonMethod.ImportTxtReadValue(this, e);

            //计算总值
            GasCommonMethod.CalcTotalValue(this);
        }

        //提交保存。//创建时间：2022-12-7 09:50:46。作者：王浩力
        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            //取样位置  //添加时间：2023-1-15 15:25:35。
            string sampling_location = cmb_quyang.SelectedValue?.ToString();
            if (!string.IsNullOrWhiteSpace(txt_quyang.Text))
            {
                // 取样位置。手动输入
                sampling_location = txt_quyang.Text.Trim();
            }

            Gas_analysis gas = new Gas_analysis()
            {
                Cate = cmb_cate.SelectedValue?.ToString(),
                Sample_no = txtYpbh.Text,
                Well_no = txtJh.Text,
                Build_name = cmb_gouzao.SelectedValue?.ToString(),
                Top_horizon = cmb_topCeng.SelectedValue?.ToString(),
                Bottom_horizon = cmb_bottomCeng.SelectedValue?.ToString(),
                Top_well_deep = top_well_deep.Text.ToMyDecimal(),
                Bottom_well_deep = bottom_well_deep.Text.ToMyDecimal(),
                Sampling_location = sampling_location,
                Samping_company_name = cmb_samping_company_name.SelectedValue?.ToString(),
                Analysis_company_name = cmb_analysis_company_name.SelectedValue?.ToString(),
                Remark = remark.Text,

                Samping_condition = cmb_samping_condition.SelectedValue?.ToString(),//取样条件
                Client = cmb_client.SelectedValue?.ToString(),
                Samping_time = dateQuyangTime.Text,//取样时间
                Analysis_time = analysis_time.Text,   //分析时间

                Samping_user = samping_user.Text,//取样人
                Analysis_user = analysis_user.Text,//分析人
                Samping_user_id = samping_user.SelectedValue.ToMyInt64(), //取样人id
                Analysis_user_id = analysis_user.SelectedValue.ToMyInt64(),

                Samping_temperature = samping_temperature.Text.ToMyDecimal(),//取样温度
                Oil_pressure = oil_pressure.Text.ToMyDecimal(), //油压
                Casing_pressure = casing_pressure.Text.ToMyDecimal(),
                Zong_s = zong_s.Text.ToMyDecimal(),  //总硫
                Water_point = water_point.Text.ToMyDecimal(),  //水露点 

                All_calc_value = txt_totalSum.Text.ToMyDecimal(),//总值
                H2Smg = txtH2S_input.Text.ToMyDecimal(),
                He = HE.Text.ToMyDecimal(),
                H2 = H2.Text.ToMyDecimal(),
                O2 = O2.Text.ToMyDecimal(),
                N2 = N2.Text.ToMyDecimal(),
                C1 = C1.Text.ToMyDecimal(),
                C6 = C6.Text.ToMyDecimal(),
                C3 = C3.Text.ToMyDecimal(),
                Ic4 = IC4.Text.ToMyDecimal(),
                Nc4 = NC4.Text.ToMyDecimal(),
                Ic5 = IC5.Text.ToMyDecimal(),
                Nc5 = NC5.Text.ToMyDecimal(),
                CO2 = CO2.Text.ToMyDecimal(),
                C2 = C2.Text.ToMyDecimal()
            };
            //是否脱硫
            byte liuTuo = (bool)radio_uoliu.IsChecked ? (byte)1 : (byte)0;
            gas.Is_desulphurization = liuTuo;

            //保存
            Gas_analysisBusiness bll = new Gas_analysisBusiness();
            var result = bll.Add(gas);
            ShowAlertHelpter.ShowAlert(result.Msg);
        }

        //计算总值
        private void C2_KeyUp(object sender, KeyEventArgs e)
        {
            //CalcTotalValue();
            GasCommonMethod.CalcTotalValue(this);

            //输入的小数位满4位，自动切换到下一行输入  //添加时间：2023-1-30 14:04:46
            var input = sender as TextBox;
            if (!string.IsNullOrWhiteSpace(input.Text) && input.Text.IndexOf(".") >= 0 && input.Text.Split('.')[1].Trim().Length == 4)
            {
                input.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
            }
        }

        ///// <summary>
        ///// 计算总值
        ///// </summary>
        //private void CalcTotalValue()
        //{
        //    //计算总值        
        //    decimal? totalSum =
        //          +He.Text.ToMyDecimal2()
        //          + H2.Text.ToMyDecimal2()
        //          + O2.Text.ToMyDecimal2()
        //          + N2.Text.ToMyDecimal2()
        //          + C1.Text.ToMyDecimal2()
        //          + C6.Text.ToMyDecimal2()
        //          + C3.Text.ToMyDecimal2()
        //          + IC4.Text.ToMyDecimal2()
        //          + NC4.Text.ToMyDecimal2()
        //          + IC5.Text.ToMyDecimal2()
        //          + NC5.Text.ToMyDecimal2()
        //          + CO2.Text.ToMyDecimal2()
        //          + C2.Text.ToMyDecimal2();

        //    //总值
        //    txt_totalSum.Text = totalSum == null ? "" : totalSum.ToString();
        //}

        //检查输入字符串是否为数字 //创建时间：2022-12-7 15:16:20，作者：王浩力
        private void samping_temperature_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            var textElem = (sender as TextBox);

            //解决连续输入很多.
            if ((
                textElem.Text.StartsWith(".") || string.IsNullOrWhiteSpace(textElem.Text)
                || textElem.Text.Contains(".")
                ) && e.Text == ".")
            {
                e.Handled = true;
                return;
            }

            //禁止在0前面继续输入0
            int index = ((System.Windows.Controls.TextBox)e.Source).CaretIndex;
            if (textElem.Text.StartsWith("0.") && index == 0 && e.Text == "0")
            {
                e.Handled = true;
                return;
            }

            //不能输入非数字
            if (Regex.IsMatch(e.Text, @"[^\d+\.{0,1}\d+]+"))
            {
                e.Handled = true;
                return;
            }
        }

        //检查输入字符串是否为数字 //创建时间：2022-12-7 15:16:20，作者：王浩力
        private void samping_temperature_PreviewKeyUp(object sender, KeyEventArgs e)
        {
            TextBox textBox = sender as TextBox;
            if (!string.IsNullOrWhiteSpace(textBox.Text))
            {
                if (textBox.Text == "0.0" || textBox.Text.StartsWith("00"))
                {
                    textBox.Text = textBox.Text.Replace("00", "");
                }
                if (!textBox.Text.StartsWith("0.") && Regex.IsMatch(textBox.Text, @"0+[1-9]+\.*\d+", RegexOptions.IgnoreCase))
                {
                    textBox.Text = textBox.Text.TrimStart('0');
                }

                //输入的不是小数或正整数           
                Regex regex = new Regex(@"[^\d+\.{0,1}\d+]", RegexOptions.IgnoreCase);
                textBox.Text = regex.Replace(textBox.Text, "");
            }
        }

    }
}
